package com.louis.iread.adapter;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;


import com.louis.iread.R;
import com.louis.iread.utils.AppUtils;

import java.util.List;

/**
 * Created by louis on 18-5-4.
 */

public class ThemeAdapter extends BaseAdapter {

    private int selected = 0;

    private Context context;
    private LayoutInflater inflater;
    private int layoutId;
    List<String> list;

    public ThemeAdapter(Context context, int layoutId, List<String> list, int selected) {
        this.context = context;
        this.layoutId = layoutId;
        this.list = list;
        this.inflater = LayoutInflater.from(this.context);
        this.selected = selected;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null) {
            convertView = inflater.inflate(layoutId, parent, false);
        }
        ImageView ivThemeBg = (ImageView) convertView.findViewById(R.id.ivThemeBg);
        ImageView ivSelected = (ImageView) convertView.findViewById(R.id.ivSelected);

        String color = (String) getItem(position);

        int colorId = AppUtils.getColorId("read_theme_"+color);
        ivThemeBg.setBackgroundColor(ContextCompat.getColor(context, colorId));

        if (selected == position) {
            ivSelected.setVisibility(View.VISIBLE);
        } else {
            ivSelected.setVisibility(View.GONE);
        }

        return convertView;
    }

    public void select(int position) {
        selected = position;
        notifyDataSetChanged();
    }

    public void select(String color) {
        for (int i = 0; i < getCount(); i++) {
            String item = (String) getItem(i);
            if (item.equals(color)) {
                selected = i;
                notifyDataSetChanged();
                return;
            }
        }
    }
}
